package com.quarkus.filter;

import lombok.extern.slf4j.Slf4j;
import org.jboss.resteasy.reactive.server.ServerRequestFilter;
import org.jboss.resteasy.reactive.server.ServerResponseFilter;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.core.Response;
import java.net.URI;

/**
 * @version v1.0
 * @Description: Request & Response Filter
 * @Author: TongRui乀
 * @Date: 2021/1/24 2:59 下午
 */
@Slf4j
public class RestServiceFilter {

    //@ServerRequestFilter(preMatching = true)
    public void preMatchingFilter(ContainerRequestContext requestContext) {
        log.info("Request Filter method:{}, path:{}", requestContext.getMethod(), requestContext.getUriInfo().getPath());
        // make sure we don't lose cheese lovers
        if("yes".equals(requestContext.getHeaderString("Cheese"))) {
            requestContext.setRequestUri(URI.create("/cheese"));
        }
    }

    //@ServerRequestFilter
    public Response getFilter(ContainerRequestContext requestContext) {
        // only allow GET methods for now
        log.info("Request Filter method:{}, path:{}", requestContext.getMethod(), requestContext.getUriInfo().getPath());
        if(requestContext.getMethod().equalsIgnoreCase(HttpMethod.GET) && !requestContext.getUriInfo().getPath().contains("flumes")) {
            // todo  提示不能使用这个方法终端线程
            //requestContext.abortWith(Response.status(Response.Status.METHOD_NOT_ALLOWED).build());
            // return null 表示继续执行
            return null;
        }
        return Response.status(404).entity("only get method permited").build();
    }

    //@ServerResponseFilter
    public void getFilter(ContainerResponseContext responseContext) {
        log.info("Response Filter");
        Object entity = responseContext.getEntity();
        if(entity instanceof String) {
            // make it shout
            responseContext.setEntity(((String)entity).toUpperCase());
        }
    }
}